<script setup>
import { Edit, Delete, Search, Shop, Connection, Comment } from '@element-plus/icons-vue'
import { ref, computed, onMounted, reactive } from 'vue'
import {
    adminGetCategoryInGoodsAPI,
    adminGetGoodsAPI,
    stateChangeAPI,
    getDetailGoodsAPI,
    recommendChangeAPI
} from '@/apis/admin'
import avatar from '@/assets/images/300.png'
import { useSellerStore } from '@/stores/sellerStore'
import router from "@/router";
const sellerStore = useSellerStore()
// -------------------------------------------分类------------------------------------------------------//
//商品分类数据模型
const category = ref([])
//获取分类数据
const getCategory = async () => {
    const res = await adminGetCategoryInGoodsAPI()
    category.value = res.data
}
onMounted(() => getCategory())

// 计算二级选项
const subCategoryOptions = computed(() => {
    const parent = category.value.find(item => item.id === categoryId.value)
    return parent?.children || [] // 返回子选项或空数组 // 返回子选项或空数组
})

// 清空二级选项值（当一级选项变化时）
const handleCategoryIdChange = () => {
    subCategoryId.value = ''
}

//-------------------------------------------查询商品------------------------------------------//
//商品列表数据模型
onMounted(() => getGoodsList())

const categoryId = ref('')//搜索时的分类id
const subCategoryId = ref('')
const state = ref('')//搜索时的发布状态
const searchName = ref('')//搜索时的搜索名字
const createUserName = ref('')//搜索时的创建人名字
const page = ref(1)//当前页//分页条数据模型
const total = ref(20)//总条数
const pageSize = ref(3)//每页条数


const goodsList = ref([])
const getGoodsList = async () => {
    //搜索参数
    let searchParams = ref({
        categoryId: categoryId.value,
        subCategoryId: subCategoryId.value,
        state: state.value,
        searchName: searchName.value,
        createUserName: createUserName.value,
        page: page.value,
        pageSize: pageSize.value
    })
    let res = await adminGetGoodsAPI(searchParams.value)

    total.value = res.data.data.counts
    goodsList.value = res.data.data.items
}

//清除搜索信息
const clearSearchInfo = () => {
    categoryId.value = ''
    subCategoryId.value = ''
    state.value = ''
    searchName.value = ''
    createUserName.value = ''
}

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    getGoodsList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    page.value = num
    getGoodsList()
}

// 创建格式化函数
const formatPayState = (payState) => {
    const stateMap = {
        1: '售卖中',
        0: '未上架'
    }
    return stateMap[payState]
}
//-------------------------------------------编辑商品------------------------------------------//
const stateChange = async (state, goodsId) => {
    const res = await stateChangeAPI(state, goodsId)
    getGoodsList()
}

const isView = ref(false)
const viewGoodsForm = ref({
    goodsImg: '',
    goodsName: '',
    content: '',
    price: '',
    goodsNumber: '',
    shippingFee: '',
    CategoryId: '',
    categoryName: '',
    SubCategoryId: ''
})
const getDetailGoods = async (goodsId) => {
    isView.value = true
    const res = await getDetailGoodsAPI(goodsId)
    viewGoodsForm.value = res.data
    console.log(res.data);
    getGoodsList()
}


// -------------------------------------------推荐修改----------------
// 判断是否包含指定推荐类型
const hasRecommend = (row, type) => {
    return row.recommends?.some(r => r.recommendType === type) || false;
};

// 推荐状态切换
const toggleRecommend = async (row, recommendType) => {
    try {
        const action = hasRecommend(row, recommendType) ? 'remove' : 'add';
        let recommendFrom = ref({
            goodsId: row.id,
            recommendType: recommendType,
            action: action
        })
        const res = await recommendChangeAPI(recommendFrom.value)

        // 更新推荐状态
        getGoodsList()

        ElMessage.success(`${action === 'add' ? '添加' : '移除'}推荐成功`);
    } catch (error) {
        ElMessage.error('操作失败，请稍后重试');
    }
};

</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>商品管理</span>
            </div>
        </template>
        <!-- 搜索表单 -->
        <!-- 一级选择 -->
        <el-form inline>
            <el-form-item label="发布状态：">
                <el-select v-model="categoryId" placeholder="一级分类" style="width: 120px;"
                    @change="handleCategoryIdChange">
                    <el-option v-for="item in category" :key="item.id" :label="item.categoryName" :value="item.id" />
                </el-select>
                <!-- 二级选择 -->
                <el-select v-model="subCategoryId" placeholder="二级分类" style="width: 120px;">
                    <!-- 空状态提示 -->
                    <el-option v-if="!subCategoryOptions.length" :value="1" disabled>
                        <span class="empty-tip">
                            {{ categoryId ? '暂无子选项' : '请先选择上级选项' }}
                        </span>
                    </el-option>
                    <!-- 正常选项 -->
                    <el-option v-for="item in subCategoryOptions" :key="item.id" :label="item.categoryName"
                        :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="发布状态：">
                <el-select placeholder="请选择" v-model="state" style="width: 100px;">
                    <el-option label="售卖中" value="1"></el-option>
                    <el-option label="待上架" value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-input :prefix-icon="Search" v-model="searchName" style="width: 200px" placeholder="请输入商品名" />
            </el-form-item>
            <el-form-item>
                <el-input :prefix-icon="Search" v-model="createUserName" style="width: 200px" placeholder="请输入创建者" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getGoodsList()">搜索</el-button>
                <el-button @click="clearSearchInfo()">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 商品列表 -->
        <el-table :data="goodsList" style="width: 100%">
            <el-table-column label="图片" prop="goodsImg">
                <template #default="{ row }">
                    <img :src="row.goodsImg" style="width: 60px; height: 60px; object-fit: cover;">
                </template>
            </el-table-column>
            <el-table-column label="商品名" prop="goodsName" width="150"></el-table-column>
            <el-table-column label="分类" prop="categoryName"></el-table-column>
            <el-table-column label="价格" prop="price"></el-table-column>
            <el-table-column label="库存" prop="goodsNumber"></el-table-column>
            <el-table-column label="人气" prop="popularity"></el-table-column>
            <el-table-column label="评论数" prop="commentNumber"></el-table-column>
            <el-table-column label="创建人" prop="createUserName"></el-table-column>
            <el-table-column label="运费" prop="shippingFee"> </el-table-column>
            <el-table-column label="状态" prop="state">
                <template #default="{ row }">
                    <span>{{ formatPayState(row.state) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="300">
                <template #default="{ row }">
                    <!-- 轮播图推荐按钮 -->
                    <el-tooltip content="设置轮播图" placement="top">
                        <el-button :type="hasRecommend(row, 1) ? 'primary' : ''"
                            :icon="hasRecommend(row, 1) ? 'Check' : 'Plus'" circle @click="toggleRecommend(row, 1)" />
                    </el-tooltip>

                    <!-- 新鲜好物推荐按钮 -->
                    <el-tooltip content="设为新鲜好物" placement="top">
                        <el-button :type="hasRecommend(row, 2) ? 'success' : ''"
                            :icon="hasRecommend(row, 2) ? 'Check' : 'Plus'" circle @click="toggleRecommend(row, 2)" />
                    </el-tooltip>

                    <!-- 人气推荐按钮 -->
                    <el-tooltip content="设为人气推荐" placement="top">
                        <el-button :type="hasRecommend(row, 3) ? 'warning' : ''"
                            :icon="hasRecommend(row, 3) ? 'Check' : 'Plus'" circle @click="toggleRecommend(row, 3)" />
                    </el-tooltip>

                    <el-button v-if="row.state === 1" class="iconfont icon-xiajia" circle plain type="info"
                        @click="stateChange(0, row.id)"></el-button>
                    <el-button :icon="Comment" circle plain type="primary"
                    @click="$router.push(`/admin/comment/${row.id}`)"></el-button>
                    <!-- @click="$router.push(`/admin/comment/${row.id}`)"></el-button> -->
                    <el-button :icon="Connection" circle plain type="primary"
                        @click="getDetailGoods(row.id)"></el-button>

                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />

        <!-- 查询商品 -->
        <el-drawer v-model="isView" title="商品信息" :before-close="handleClose" direction="rtl" size="40%">
            <el-descriptions direction="vertical" border style="margin-top: 20px">
                <el-descriptions-item :rowspan="2" :width="140" label="图片" align="center">
                    <el-image style="width: 100px; height: 100px" :src="viewGoodsForm.goodsImg" />
                </el-descriptions-item>

                <el-descriptions-item label="商品名">{{ viewGoodsForm.goodsName }}</el-descriptions-item>
                <el-descriptions-item label="分类">{{ viewGoodsForm.categoryName }}</el-descriptions-item>
                <el-descriptions-item label="价格">{{ viewGoodsForm.price }}</el-descriptions-item>
                <el-descriptions-item label="库存">{{ viewGoodsForm.goodsNumber }}</el-descriptions-item>

                <!-- 商品描述单独一行 -->
                <el-descriptions-item :span="24" label="商品描述">
                    {{ viewGoodsForm.content }}
                </el-descriptions-item>

                <!-- 其他图片单独一行 -->
                <el-descriptions-item :span="24" label="其他图片">
                    <el-empty v-if="!viewGoodsForm.mainImg?.length" description="暂无其他图片" />
                    <div v-else style="display: flex; gap: 10px; overflow-x: auto;">
                        <el-image v-for="(img, index) in viewGoodsForm.mainImg" :key="index"
                            style="width: 100px; height: 100px; flex-shrink: 0;" :src="img"
                            :preview-src-list="viewGoodsForm.mainImg" fit="cover" />
                    </div>
                </el-descriptions-item>
            </el-descriptions>
        </el-drawer>
    </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.avatar-uploader {
    :deep() {
        .avatar {
            width: 150px;
            height: 150px;
            display: block;
        }
    }
}
</style>